/**
 * 项目列表获取接口测试用例
 *
 * Created by snowingsea on 2020/02/09.
 */
const chai = require('chai');
const should = chai.should(); // eslint-disable-line no-unused-vars
chai.use(require('chai-http'));

const common = require('./../../common');
const Administrator = require('./../../../models/administrator');
const uri = require('./../uri');
const { statusKind } = require('./../../../../phoenix/models/projects');

module.exports = describe('/GET projects.json', function () {
  const url = '/projects.json';
  const administrator = new Administrator();
  let tester;
  const projectCount = 13;
  let anotherTester;
  const anotherTesterProjectCount = 3;
  const newUserIds = [];
  function getTester() {
    return tester;
  }

  before(function (done) {
    administrator.login()
      .then(() => administrator.createRandomTester())
      .then((res) => {
        tester = res;
        newUserIds.push(tester.userId);
        return tester.createRandomProjects(projectCount);
      })
      .then((projects) => tester.randomFreezeProjects(projects))
      .then(() => administrator.createRandomTester())
      .then((res) => {
        anotherTester = res;
        newUserIds.push(anotherTester.userId);
        return res.createRandomProjects(anotherTesterProjectCount);
      })
      .then(() => {
        done();
      })
      .catch(done);
  });
  after(function (done) {
    administrator.removeUsers(newUserIds)
      .then(() => {
        done();
      })
      .catch(done);
  });

  common.should.be.user(uri, url, 'get');
  common.should.be.tester(uri, url, 'get');
  const sortByKeys = ['projectId', 'projectName', 'createAt', 'visitAt'];
  common.should.complete.filter(uri, url, 'get', getTester, sortByKeys);

  // 正常获取项目列表
  it('it should GET projects', function (done) {
    tester.login()
      .then(() => {
        chai.request(uri)
          .get(url)
          .set('Authorization', `Bearer ${tester.token.accessToken}`)
          .end((err, res) => {
            res.should.have.status(200);
            common.should.be.projectsMessage(res.body);
            res.body.pagination.total.should.be.eql(projectCount);
            done();
          });
      })
      .catch(done);
  });

  // 搜索
  it('it should search the project by keyword', function (done) {
    let newProject;
    tester.createRandomProject()
      .then((res) => {
        newProject = res;
        return tester.login();
      })
      .then(() => {
        chai.request(uri)
          .get(url)
          .query({ q: newProject.projectName })
          .set('Authorization', `Bearer ${tester.token.accessToken}`)
          .end((err, res) => {
            res.should.have.status(200);
            common.should.be.projectsMessage(res.body);
            res.body.pagination.total.should.be.eql(1);
            res.body.projects[0].projectName.should.be.eql(newProject.projectName);
            done();
          });
      })
      .catch(done);
  });

  // 筛选
  const filters = [
    { status: statusKind.normal },
    { status: statusKind.frozen },
  ];
  filters.forEach((filter) => {
    it(`it should get projects with ${JSON.stringify(filter)}`, function (done) {
      tester.login()
        .then(() => {
          chai.request(uri)
            .get(url)
            .query(filter)
            .set('Authorization', `Bearer ${tester.token.accessToken}`)
            .end((err, res) => {
              res.should.have.status(200);
              common.should.be.projectsMessage(res.body);
              res.body.projects.forEach((project) => {
                Object.keys(filter).forEach((key) => {
                  project[key].should.be.eql(filter[key]);
                });
              });
              done();
            });
        })
        .catch(done);
    });
  });

  // 项目访问后访问时间排序变动
  it('it should change when one of project is visited', function (done) {
    tester.login()
      .then(() => {
        const query = { sortBy: 'visitAt', order: 'desc' };
        chai.request(uri)
          .get(url)
          .query(query)
          .set('Authorization', `Bearer ${tester.token.accessToken}`)
          .end((err, res) => {
            res.should.have.status(200);
            common.should.be.projectsMessage(res.body);
            const lastProject = res.body.projects[res.body.projects.length - 1];
            tester.getProject(lastProject.projectId)
              .then(() => {
                chai.request(uri)
                  .get(url)
                  .query(query)
                  .set('Authorization', `Bearer ${tester.token.accessToken}`)
                  .end((err, res) => {
                    res.should.have.status(200);
                    common.should.be.projectsMessage(res.body);
                    res.body.projects[0].projectId.should.be.eql(lastProject.projectId);
                    res.body.projects[0].visitAt.should.not.be.eql(lastProject.visitAt);
                    done();
                  });
              })
              .catch(done);
          });
      })
      .catch(done);
  });

  // 新添加的项目应当在按访问排序第一位
  it('it should be first of projects sort by "visitAt" when add a new project', function (done) {
    let firstProjectId;
    tester.createRandomProject()
      .then(({ projectId }) => {
        firstProjectId = projectId;
        return tester.login();
      })
      .then(() => {
        chai.request(uri)
          .get(url)
          .query({ sortBy: 'visitAt', order: 'desc' })
          .set('Authorization', `Bearer ${tester.token.accessToken}`)
          .end((err, res) => {
            res.should.have.status(200);
            common.should.be.projectsMessage(res.body);
            res.body.projects[0].projectId.should.be.eql(firstProjectId);
            done();
          });
      })
      .catch(done);
  });

  // 新添加项目删除所有版本后应该还在第一位且无lastVersion字段
  it('it should be first of projects sort by "visitAt" when add a new project without versions', function (done) {
    let firstProjectId;
    tester.createRandomProject()
      .then((project) => {
        firstProjectId = project.projectId;
        return project.removeVersion(project.lastVersion.versionId);
      })
      .then(() => tester.login())
      .then(() => {
        chai.request(uri)
          .get(url)
          .query({ sortBy: 'visitAt', order: 'desc' })
          .set('Authorization', `Bearer ${tester.token.accessToken}`)
          .end((err, res) => {
            res.should.have.status(200);
            common.should.be.projectsMessage(res.body);
            res.body.projects[0].projectId.should.be.eql(firstProjectId);
            res.body.projects[0].should.not.have.property('lastVersion');
            done();
          });
      })
      .catch(done);
  });
});
